﻿// This is the *viewmodel* - defines the data and behavior of the testimonial UI
function Testimonial(data) {
    this.TestimonialID = ko.observable(data.TestimonialID);
    this.Testimonial = ko.observable(data.Testimonial);
    this.AuthorFirstName = ko.observable(data.AuthorFirstName);
    this.AuthorLastName = ko.observable(data.AuthorLastName);
    this.AuthorLocation = ko.observable(data.AuthorLocation);
    this.IsPublished = ko.observable(data.IsPublished);
    this.TestimonialDate = ko.observable(data.TestimonialDate);
    this.AuthorFirstNameInitial = ko.computed(function () {
        return this.AuthorFirstName().substring(0, 1);
    }, this);
    this.AuthorLastNameInitial = ko.computed(function () {
        return this.AuthorLastName().substring(0, 1);
    }, this);
}

function TestimonialInfoDTO(testimonialID, isPublished) {
    this.TestimonialID = testimonialID;
    this.IsPublished = isPublished;
}

function TestimonialViewModel() {

    /***************************
    * private vars 
    ****************************/
    var self = this;
    var sf; //reference to the dnn services framework
    //used to hold user notifications of activity during this session
    self.userAlertText = ko.observable();
    self.newTestimonialText = ko.observable();
    self.newAuthorFirstNameText = ko.observable();
    self.newAuthorLastNameText = ko.observable();
    self.newAuthorLocationText = ko.observable();

    //collection of all testimonials
    self.testimonials = ko.observableArray([]);

    //lists all of the testimonials that are currently published live
    self.collection_publishedTestimonials = ko.computed(function () {
        return ko.utils.arrayFilter(self.testimonials(), function (item) {
            return (item.IsPublished())
        });
    });

    //lists all of the testimonials that are currently NOT published live 
    // AND DO NOT HAVE any 'pending' activities
    self.collection_unpublishedTestimonials = ko.computed(function () {
        return ko.utils.arrayFilter(self.testimonials(), function (item) {
            return (!item.IsPublished())
        });
    });

    /****************************************/
    /********* CRUD OPERATIONS***************/
    /****************************************/
    //C//operations - add not required. add is handled via webform module

    //R//operations - gets all testimonials in the system {published and/or unpublished}
    self.getTestimonials = function () {
        //Load initial state from the server, convert to Testimonial instances and then populate self.Testionials
        var method = "GetTestimonials";
        var testimonials = self.testimonials;
        $.ajax({
            type: "GET",
            url: sf.getServiceRoot('VirtualEssentials/Testimonials') + "TestimonialWeb/" + method,
            beforeSend: sf.setModuleHeaders,
            data: {},
            success: function (data) {
                var mappedTestimonials = $.map(data, function (item) { return new Testimonial(item) });
                self.testimonials(mappedTestimonials);
            },
            error: function (xhr, status, error) {
                alert(error);
            }
        });
    };

    //U//operation - update
    self.updateTestimonial = function (objItem) {
        var method = "UpdateTestimonial";
        self.UpdatePublishStatus(objItem);
        var data = new TestimonialInfoDTO(objItem.TestimonialID(), objItem.IsPublished());

        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: sf.getServiceRoot('VirtualEssentials/Testimonials') + "TestimonialWeb/" + method,
            beforeSend: sf.setModuleHeaders,
            data: ko.toJSON(data),
            success: function (data) {
                self.userAlertText(objItem.Testimonial() + ' changes have been saved');
                //self.getTestimonials(); //get the new data after updates
            },
            error: function (xhr, status, error) {
                self.userAlertText('OOPS! Error updating ' + objItem.Testimonial + '<br />' + (error));
                //put the status back
                self.UpdatePublishStatus(objItem);

            }
        });
    };
    //D//operations - delete
    self.deleteTestimonial = function (objItem) {
        var data = new TestimonialInfoDTO(objItem.TestimonialID(), objItem.IsPublished());
        if (confirm("Are you sure you want to delete this item? It cannot be undone...")) {
            //does the observable array "testimonials" update itself in this case?
            //self.Testimonials.remove(objItem)
            var method = "DeleteTestimonial";
            $.ajax({
                type: "POST",
                contentType: "application/json",
                url: sf.getServiceRoot('VirtualEssentials/Testimonials') + "TestimonialWeb/" + method,
                beforeSend: sf.setModuleHeaders,
                data: ko.toJSON(data),
                success: function (data) {
                    self.userAlertText(objItem.Testimonial() + ' has been deleted.');
                    self.testimonials.remove(objItem);
                },
                error: function (xhr, status, error) {
                    self.userAlertText('OOPS! Error updating ' + objItem.Testimonial + '<br />' + (error));
                }
            });
        } else {
            //do nothing
        }
    };


    /****************************************/
    /********** HELPER FUNCTIONS ************/
    /****************************************/
    //switch the publish status based on current..used in data ops
    self.UpdatePublishStatus = function (objItem) {
        if (objItem.IsPublished() == true) {
            objItem.IsPublished(false);
        } else {
            objItem.IsPublished(true);
        }
    };

    /** The 'Active Module' is used in the asp.net/dnn library code behind
    to allow the WebAPI to have a reference to the "active module". In order
    for this to work, a call to the client side services framework must be made
    where the current module id and text id are passed to it**/
    self.setUpActiveModule = function () {
        var ModuleId = $('.veModuleId').text();
        var tabID = $('.veTabID').text();
        sf = $.ServicesFramework(ModuleId);
        sf.setModuleHeaders;
    };

    /**********************************/
    /********** PAGE_ONLOAD************/
    /**********************************/
    self.setUpActiveModule(); //set up the active module PRIOR to making any webapi calls
    self.getTestimonials(); //load the initial dataset.

}